;(function(){
	
	$.fn.linkageSel = function(options){
		
		defaults = $.extend({
			url: '#',
			series: 10,
			defVal: [],
			defCountry: 100000,
			data: {id:'0'},
			returnValue: function(){
			}
		},options);
		
		this.opts = $.extend(defaults, options);
		this.bind();
		
		return;
	}
	
	$.fn.bind = function(){
		
		var t = this;
		var opt = this.opts;
		
		if(opt==undefined) return;
		
		this.initialObj = {
			con: $('<div class="hd-select-city"></div>'),
			country: $('<div class="select-country"></div>'),
			coTitle: $('<div class="country-title">请选择国家</div>'),
			coval: $('<input type="hidden" />'),
			coWrap: $('<div class="country-select-warp"></div>'),
			wrap: $('<div class="select-city"></div>'),
			ciTitle: $('<div id="city-title" class="city-title">请选择省市区</div>'),
			cival: $('<input type="hidden" value="'+opt.defCountry+'" />'),
			tab_txt: ''
		}
		
		var h = this.initialObj;
		
		h.country.append(h.coTitle,'<div class="menu-button-dropdown"></div>',h.coval,h.coWrap);
		h.wrap.append(h.ciTitle,'<div class="menu-button-dropdown"></div>',h.cival);
		this.setCountry();
		h.con.append(h.country,h.wrap);
		$(this).replaceWith(this.initialObj.con);
		
		if(this.opts.defVal.length>0) this.autoFill();
		this.cityHand();
		
	}
	
	$.fn.autoFill = function(){
		
		var o = this;
		var opt = this.opts;
		var fill = '';
		this.cityContent(opt.defVal[0]);
		$("#city-component").addClass("ct-overlay-hidden");
		for(var i=0;i<opt.defVal.length;i++){
			if(i>0&&i<$(".city-select").length){
				var d = this.getRemoteData(opt.defVal[i]);
				var _html = o.returnHtml(d);
				$(".city-select").eq(i).html('<dl class="fn-list"><dd>'+_html+'</dd></dl>');
			}
			if(i<$(".city-select").length){
				$.each($(".city-select").eq(i).find("a"), function() {
					if($(this).data('id') == opt.defVal[i+1]){
						if(i==0){
							fill += $(this).html();
						}else{
							fill += '<span>/</span>'+$(this).html();
						}
						$(this).addClass("current");
					}
				});
			}
		}
		$("#city-title").html(fill).addClass("has-city-title");
		
	}
	
	$.fn.setCountry = function(){
		
		var _this = this;
		var h = this.initialObj;
		$.each(this.getRemoteData(0), function(){
			h.coWrap.append('<a href="javascript:;" data-id="'+this.id+'" data-level="'+this.level+'" data-text="'+this.location+'">'+this.name+'</a>');
			if(_this.opts.defCountry==this.id){
				h.coTitle.html(this.name);
				h.coval.val(this.id);
				h.tab_txt = this.location;
			}
		});
		
		h.coWrap.on('click','a',function(e){
			$(this).addClass("selected").siblings().removeClass("selected");
			h.coTitle.html($(this).html());
			h.coWrap.hide();
			if($(this).data("id")!=_this.opts.defCountry){
				h.coval.val($(this).data("id"));
				$("#city-component").remove();
				h.tab_txt = $(this).data("text");
				_this.opts.defCountry = $(this).data("id");
				$("#city-title").html('请选择省市区').removeClass("has-city-title");
			}
			e.stopPropagation();
		});
		
		h.country.on('click',function(e){
			h.coWrap.show();
			$("#city-component").addClass("ct-overlay-hidden");
			e.stopPropagation();
		});
		
	}
	
	$.fn.cityContent = function(n){
		
		var o = this;
		var h = this.initialObj;
		var opt = this.opts;
		
		var tab_name = h.tab_txt.split(",");
		o.opts.series = tab_name.length;
		var tab_html = '';
		var tab_width = 300/tab_name.length;
		for(var i=0;i<tab_name.length;i++){
			if(i==0){
				tab_html += '<a data-cont="city-'+tab_name[i]+'" style="width:'+tab_width+'px;" class="current">'+tab_name[i]+'</a>';
			}else{
				tab_html += '<a data-cont="city-'+tab_name[i]+'" style="width:'+tab_width+'px;">'+tab_name[i]+'</a>';
			}
			
		}
		var _html = o.fillProvince(o.getRemoteData(n));
		var _con = '<div id="city-component" class="ct-overlay">'
					+'	<div class="city-select-warp">'
					+'		<div class="city-select-tab">'+tab_html+'</div>'
					+'		<div class="city-select-content">'
					+'			<div class="city-select city-province" style="display:block;">'+_html+'</div>'
					+'			<div class="city-select city-city"></div>'
					+'			<div class="city-select city-district"></div>'
					+'			<div class="city-select city-street"></div>'
					+'		</div>'
					+'	</div>'
					+'</div>';
		
		$(".select-city").append(_con)
		
	}
	
	$.fn.cityHand = function(){
		
		var o = this;
		var h = this.initialObj;
		var opt = this.opts;

		$(".select-city").live('click',function(e){
			if($("#city-component").length>0){
				$("#city-component").removeClass("ct-overlay-hidden");
			}else{
				o.cityContent(opt.defCountry);
			}
			$(".country-select-warp").hide();
			e.stopPropagation();
		})
		
		//切换
		$(".city-select-tab a").live('click',function(){
			$(this).addClass("current").siblings().removeClass("current");
			$("#city-component").find(".city-select").eq($(this).index()).show().siblings().hide();
		});
		
		//省份
		$(".city-province a").live('click',function(){
			$(this).addClass("current").siblings().removeClass("current");
			$(".city-district").html("");
			$(".city-street").html("");
			var _html = o.returnHtml(o.getRemoteData($(this).data("id")));
			$(".city-city").html('<dl class="fn-list"><dd>'+_html+'</dd></dl>');
			$(".city-select-tab").find("a").eq(1).trigger("click");
			o.returnSelectedAddress(1);
		});
		
		//城市
		$(".city-city a").live('click',function(){
			$(this).addClass("current").siblings().removeClass("current");
			$(".city-street").html("");
			var _html = o.returnHtml(o.getRemoteData($(this).data("id")));
			$(".city-district").html('<dl class="fn-list"><dd>'+_html+'</dd></dl>');
			$(".city-select-tab").find("a").eq(2).trigger("click");
			o.returnSelectedAddress(2);
		});
		
		//区县
		$(".city-district a").live('click',function(){
			$(this).addClass("current").siblings().removeClass("current");
			var _html = o.returnHtml(o.getRemoteData($(this).data("id")));
			$(".city-street").html('<dl class="fn-list"><dd>'+_html+'</dd></dl>');
			$(".city-select-tab").find("a").eq(3).trigger("click");
			o.returnSelectedAddress(3);
		});
		
		//街道
		$(".city-street a").live('click',function(){
			$(this).addClass("current").siblings().removeClass("current");
			o.returnSelectedAddress(4);
		});
	
		$(window).click(function(){
			$("#city-component").addClass("ct-overlay-hidden");
			$(".country-select-warp").hide();
		});
		
	}
	
	$.fn.fillProvince = function(d){
		
		var h = this.initialObj;
		//字母排序
		var sortBy = function (filed, rev, primer) {
		    rev = (rev) ? -1 : 1;
		    return function (a, b) {
		        a = a[filed];
		        b = b[filed];
		        if (typeof (primer) != 'undefined') {
		            a = primer(a);
		            b = primer(b);
		        }
		        if (a < b) { return rev * -1; }
		        if (a > b) { return rev * 1; }
		        return 1;
		    }
		};
		
		var $json =	new Array();
		var flog = true;
		
		$.each(d,function(){
			var t = this;
			if(t.pinyin == '' || t.pinyin == null || t.pinyin == undefined){
				$json.push({"pyid":"0","name":t.name,"id":t.id,"level":t.level,"parent":t.parent_id});
				flog = false;
			}else{
				$json.push({"pyid":t.pinyin.charAt(0),"name":t.name,"id":t.id,"level":t.level,"parent":t.parent_id});
			}
		});
	
		if(flog){
			$json.sort(sortBy('pyid', false, String));//进行首字母排序
			var t1 = t2 = t3 = t4 = '';
			var v1 =  new RegExp("^[a-g]+$");
			var v2 =  new RegExp("^[h-k]+$");
			var v3 =  new RegExp("^[l-s]+$");
			var v4 =  new RegExp("^[t-z]+$");
			$.each($json, function() {
				switch (true)
				{
					case v1.test(this.pyid):
						t1 += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
						break;
					case v2.test(this.pyid):
						t2 += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
						break;
					case v3.test(this.pyid):
						t3 += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
						break;
					case v4.test(this.pyid):
						t4 += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
						break;
					default:
				}
			});
			var ag = '<dl class="fn-list"><dt>A-G</dt><dd>'+t1+'</dd></dl>';
			var hk = '<dl class="fn-list"><dt>H-K</dt><dd>'+t2+'</dd></dl>';
			var ls = '<dl class="fn-list"><dt>L-S</dt><dd>'+t3+'</dd></dl>';
			var tz = '<dl class="fn-list"><dt>T-Z</dt><dd>'+t4+'</dd></dl>';
			return ag+hk+ls+tz;
		}else{
			var txt = '';
			$.each($json, function(){
				txt += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
			});
			return '<dl class="fn-list no-dt"><dd>'+txt+'</dd></dl>';
		}
		
	}
	
	$.fn.returnSelectedAddress = function(n){
	
		var id = [];
		var _title = '';
		$(".city-select").each(function(i){
			if($(this).find(".current").data("id")!=undefined){
				id.push($(this).find(".current").data("id"));
			}
			if($(this).find(".current").html()!=null){
				if(i==0){
					_title += $(this).find(".current").html();
				}else{
					_title += '<span>/</span>'+$(this).find(".current").html();
				}
			}
		});
		if(_title!=''){
			$("#city-title").html(_title).addClass("has-city-title");
		}
		if(this.opts.series==n){
			setTimeout(function(){
				$(window).trigger("click");
			},10);
		}
		return this.opts.returnValue(id);
		
	}
	
	$.fn.returnHtml = function(d){
		
		var _html = '';
		$.each(d, function() {
			_html += '<a title="'+this.name+'" data-id="'+this.id+'" data-parent-id="'+this.parent+'" data-level="'+this.level+'" href="javascript:;">'+this.name+'</a>';
		});
		return _html;
		
	}
	
	$.fn.getRemoteData = function(d){
		
		var opt = this.opts;
		var f = {
			cache: false,
			async: false, 
	        type: 'post',
	        url: opt.url,
	        data: {id:d},
	        dataType: 'json',
	        success: function(data){
	        	datas = data;
	        }
		}
		
		$.ajax(f);
		
		return datas;
		
	}
	
})(jQuery);